package com.linkage.admin.interceptor;

import java.lang.reflect.Method;

import com.linkage.user.pojo.User;

import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * 检查是否登录的spring拦截器
 * 
 * @author sunhao(sunhao.java@gmail.com)
 * @version V1.0
 * @createTime 2012-2-18 下午06:14:15
 */
public class AdminLoginInterceptor extends HandlerInterceptorAdapter {
	/**
     * 在Controller方法前进行拦截
     *
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
	    HandlerMethod handlerMethod = (HandlerMethod) handler;
        Method method = handlerMethod.getMethod();
        
        //获取注解
        NeedAdminLogin nl = method.getAnnotation(NeedAdminLogin.class);
        
        if(nl == null) {
            return super.preHandle(request, response, handler);
        }
                                                                                                                                                                                                                                                                                                         	
        HttpSession session = request.getSession(true);
        User loginUser = (User) session.getAttribute("LOGIN_USER_KEY_IN_SESSION");

		if(loginUser == null || !("admin".equals(loginUser.getUserName()))){
			response.sendRedirect(request.getContextPath() + "/admin/gotoAdminLogin");
		} else {
			request.setAttribute("loginUser", loginUser);
			return super.preHandle(request, response, handler);
		}

		return false;
	}

	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
	    request.setAttribute("loginUser", request.getSession().getAttribute("LOGIN_USER_KEY_IN_SESSION"));
		super.postHandle(request, response, handler, modelAndView);
	}

	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
	    request.setAttribute("loginUser", request.getSession().getAttribute("LOGIN_USER_KEY_IN_SESSION"));
		super.afterCompletion(request, response, handler, ex);
	}
}
